package com.lvmama.rhino.web;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lvmama.rhino.enums.NewCategoryEnum;
import com.lvmama.rhino.pojo.RepruchaseAnalysis;
import com.lvmama.rhino.pojo.RepruchaseAnalysisQuery;
import com.lvmama.rhino.pojo.RepurchaseCategory;
import com.lvmama.rhino.pojo.RepurchaseRateVO;
import com.lvmama.rhino.service.RepurchaseService;
import com.lvmama.rhino.utils.DateUtil;

/** 复购分析
 * @author caoyong
 * @version 1.0.0
 * @since 2018-03-22 10:36
 **/
@Controller
@RequestMapping("repurchase")
public class RepurchaseController {
    private Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private RepurchaseService repurchaseService;

    @RequestMapping("distribution")
    public String repurchaseAnalysis(Model model, HttpServletRequest request) {
        log.info("repurchaseAnalysis start.");
        String chooseTime = request.getParameter("chooseTime");
        try {
            List<RepurchaseCategory> repurchaseCategoryList = new ArrayList<>();
            RepruchaseAnalysisQuery query = new RepruchaseAnalysisQuery();
            if (!StringUtils.isEmpty(chooseTime)){
            	Map<String, Date> map = DateUtil.getSelectDate(chooseTime);
            	if(map != null && !map.isEmpty() && map.containsKey("beginDate") && map.containsKey("endDate")){
            		query.setStartTime(map.get("beginDate"));
            		query.setEndTime(map.get("endDate"));
    	         }
            }
           //查询最近记录
            RepruchaseAnalysis repruchaseAnalysis = repurchaseService.selectLatestRecord();
            //当查询时间段为空则查询最近记录
            if (query.getStartTime() == null && query.getEndTime() == null){
            	 query.setCreateTime(repruchaseAnalysis.getCreateTime());
            }
           
            List<RepruchaseAnalysis> repruchaseAnalysisList = repurchaseService.queryRepruchaseAnalysisList(query);
            for (NewCategoryEnum en : NewCategoryEnum.values()) {
                if (null != en.getShowName()) {
                    RepurchaseCategory category = new RepurchaseCategory();
                    category.setCategoryType(en.getShowName());
                    for (RepruchaseAnalysis re : repruchaseAnalysisList) {
                        if (en.getValue().equals(re.getCategory())) {
                            switch (re.getBusinessType()) {
                                case "01":
                                    category.setDomesticTicket(re.getNum());
                                    break;
                                case "02":
                                    category.setOverseasTicket(re.getNum());
                                    break;
                                case "04":
                                    category.setHotel(re.getNum());
                                    break;
                                case "05":
                                    category.setHotelTicket(re.getNum());
                                    break;
                                case "06":
                                    category.setLongGroup(re.getNum());
                                    break;
                                case "07":
                                    category.setAroundGroup(re.getNum());
                                    break;
                                case "08":
                                    category.setFreeWalker(re.getNum());
                                    break;
                                case "09":
                                    category.setOverseasGroup(re.getNum());
                                    break;
                                case "10":
                                    category.setOverseasFreeWalker(re.getNum());
                                    break;
                                case "11":
                                    category.setOverseasCruiseShip(re.getNum());
                                    break;
                                case "12":
                                    category.setOverseasOther(re.getNum());
                                    break;
                                case "98":
                                    category.setTrainTicket(re.getNum());
                                    break;
                                case "99":
                                    category.setAirTicket(re.getNum());
                                    break;
                                case "102":
                                    category.setDownRepurchaseUser(re.getNum());
                                    break;
                            }
                        }
                    }
                    repurchaseCategoryList.add(category);
                }
            }
            //101
            RepurchaseCategory lastMonthUser = getPurchaseCategoryByBusinessType(NewCategoryEnum.LAST_MONTH_USER.getCode(), repruchaseAnalysis.getCreateTime());
            lastMonthUser.setCategoryType(NewCategoryEnum.LAST_MONTH_USER.getValue());
            //103
            RepurchaseCategory other = getPurchaseCategoryByBusinessType(NewCategoryEnum.OTHER_REPURCHASE.getCode(), repruchaseAnalysis.getCreateTime());
            other.setCategoryType(NewCategoryEnum.OTHER_REPURCHASE.getValue());
            //104
            RepurchaseCategory up = getPurchaseCategoryByBusinessType(NewCategoryEnum.UP_REPURCHASE_USER.getCode(), repruchaseAnalysis.getCreateTime());
            up.setCategoryType(NewCategoryEnum.UP_REPURCHASE_USER.getValue());
            repurchaseCategoryList.add(other);
            repurchaseCategoryList.add(up);
            //新品类
            model.addAttribute("repurchaseCategories", repurchaseCategoryList);
            model.addAttribute("categories", NewCategoryEnum.getTableShowNameEnum());
            model.addAttribute("lastMonthUser", lastMonthUser);
            //计算复购率矩阵
            List<RepurchaseCategory> repurchaseCategoryRateList = new ArrayList<>();
            for (RepurchaseCategory repurchaseCategory : repurchaseCategoryList) {
                RepurchaseCategory repurchaseCategoryRate = new RepurchaseCategory();
                repurchaseCategoryRate.setCategoryType(repurchaseCategory.getCategoryType());
                repurchaseCategoryRate.setDomesticTicket(divide(repurchaseCategory.getDomesticTicket(), lastMonthUser.getDomesticTicket()));
                repurchaseCategoryRate.setOverseasTicket(divide(repurchaseCategory.getOverseasTicket(), lastMonthUser.getOverseasTicket()));
                repurchaseCategoryRate.setHotel(divide(repurchaseCategory.getHotel(), lastMonthUser.getHotel()));
                repurchaseCategoryRate.setHotelTicket(divide(repurchaseCategory.getHotelTicket(), lastMonthUser.getHotelTicket()));
                repurchaseCategoryRate.setLongGroup(divide(repurchaseCategory.getLongGroup(), lastMonthUser.getLongGroup()));
                repurchaseCategoryRate.setAroundGroup(divide(repurchaseCategory.getAroundGroup(), lastMonthUser.getAroundGroup()));
                repurchaseCategoryRate.setFreeWalker(divide(repurchaseCategory.getFreeWalker(), lastMonthUser.getFreeWalker()));
                repurchaseCategoryRate.setOverseasGroup(divide(repurchaseCategory.getOverseasGroup(), lastMonthUser.getOverseasGroup()));
                repurchaseCategoryRate.setOverseasFreeWalker(divide(repurchaseCategory.getOverseasFreeWalker(), lastMonthUser.getOverseasFreeWalker()));
                repurchaseCategoryRate.setOverseasCruiseShip(divide(repurchaseCategory.getOverseasCruiseShip(), lastMonthUser.getOverseasCruiseShip()));
                repurchaseCategoryRate.setOverseasOther(divide(repurchaseCategory.getOverseasOther(), lastMonthUser.getOverseasOther()));
                repurchaseCategoryRate.setTrainTicket(divide(repurchaseCategory.getTrainTicket(), lastMonthUser.getTrainTicket()));
                repurchaseCategoryRate.setAirTicket(divide(repurchaseCategory.getAirTicket(), lastMonthUser.getAirTicket()));
                repurchaseCategoryRate.setDownRepurchaseUser(divide(repurchaseCategory.getDownRepurchaseUser(), lastMonthUser.getDownRepurchaseUser()));
                repurchaseCategoryRateList.add(repurchaseCategoryRate);
            }
            model.addAttribute("repurchaseCategoriesRate", repurchaseCategoryRateList);
            if (!StringUtils.isEmpty(chooseTime)){
            	model.addAttribute("chooseTime", chooseTime);
            }
        } catch (Exception e) {
            log.info("repurchaseAnalysis error:." + e.getMessage(), e);
        }
        log.info("repurchaseAnalysis end.");
        return "/application/repurchase/repurchaseDistribution";
    }

    private RepurchaseCategory getPurchaseCategoryByBusinessType(String businessType, Date createTime) {
        RepruchaseAnalysisQuery query = new RepruchaseAnalysisQuery();
        query.setCreateTime(createTime);
        query.setBusinessType(businessType);
        List<RepruchaseAnalysis> repruchaseAnalysisList = repurchaseService.queryRepruchaseAnalysisList(query);
        RepurchaseCategory lastMonthUser = new RepurchaseCategory();
        for (RepruchaseAnalysis re : repruchaseAnalysisList) {
            NewCategoryEnum categoryEnum = NewCategoryEnum.getEnumByValue(re.getCategory());
            if (null != categoryEnum) {
                switch (categoryEnum) {
                    case DOMESTIC_TICKET:
                        lastMonthUser.setDomesticTicket(re.getNum());
                        break;
                    case OVERSEAS_TICKET:
                        lastMonthUser.setOverseasTicket(re.getNum());
                        break;
                    case HOTEL:
                        lastMonthUser.setHotel(re.getNum());
                        break;
                    case HOTEL_TICKET:
                        lastMonthUser.setHotelTicket(re.getNum());
                        break;
                    case LONG_GROUP:
                        lastMonthUser.setLongGroup(re.getNum());
                        break;
                    case AROUND_GROUP:
                        lastMonthUser.setAroundGroup(re.getNum());
                        break;
                    case FREE_WALKER:
                        lastMonthUser.setFreeWalker(re.getNum());
                        break;
                    case OVERSEAS_GROUP:
                        lastMonthUser.setOverseasGroup(re.getNum());
                        break;
                    case OVERSEAS_FREE_WALKER:
                        lastMonthUser.setOverseasFreeWalker(re.getNum());
                        break;
                    case OVERSEAS_CRUISE_SHIP:
                        lastMonthUser.setOverseasCruiseShip(re.getNum());
                        break;
                    case OVERSEAS_OTHER:
                        lastMonthUser.setOverseasOther(re.getNum());
                        break;
                    case TRAIN_TICKET:
                        lastMonthUser.setTrainTicket(re.getNum());
                        break;
                    case AIR_TICKET:
                        lastMonthUser.setAirTicket(re.getNum());
                        break;

                }
            }
        }
        if (NewCategoryEnum.OTHER_REPURCHASE.getCode().equals(businessType)) {
            lastMonthUser.setDownRepurchaseUser("");
        } else if (NewCategoryEnum.LAST_MONTH_USER.getCode().equals(businessType)) {
            //查询上月下单用户总数
            RepruchaseAnalysisQuery queryLastSum = new RepruchaseAnalysisQuery();
            queryLastSum.setCreateTime(createTime);
            queryLastSum.setBusinessType(NewCategoryEnum.LAST_MONTH_USER_ALL.getCode());
            List<RepruchaseAnalysis> lastSumList = repurchaseService.queryRepruchaseAnalysisList(queryLastSum);
            if (null != lastSumList && !lastSumList.isEmpty()) {
                String num = lastSumList.get(0).getNum();
                lastMonthUser.setDownRepurchaseUser(StringUtils.isNotBlank(num) ? num : "0");
            }
        } else if (NewCategoryEnum.UP_REPURCHASE_USER.getCode().equals(businessType)) {
            //查询上游复购用户总数
            RepruchaseAnalysisQuery queryUpSum = new RepruchaseAnalysisQuery();
            queryUpSum.setCreateTime(createTime);
            queryUpSum.setBusinessType(NewCategoryEnum.UP_REPURCHASE_USER_ALL.getCode());
            List<RepruchaseAnalysis> upSumList = repurchaseService.queryRepruchaseAnalysisList(queryUpSum);
            if (null != upSumList && !upSumList.isEmpty()) {
                String num = upSumList.get(0).getNum();
                lastMonthUser.setDownRepurchaseUser(StringUtils.isNotBlank(num) ? num : "0");
            }
        }
        return lastMonthUser;
    }

    private String divide(String num1, String num2) {
        if (StringUtils.isBlank(num1) || StringUtils.isBlank(num2) || "0".equals(num1) || "0".equals(num2)) {
            return "0.00%";
        }
        BigDecimal num = new BigDecimal(num1).multiply(new BigDecimal("100")).divide(new BigDecimal(num2), 2, BigDecimal.ROUND_HALF_UP);
        //格式化
        DecimalFormat fm = new DecimalFormat("0.00");
        return fm.format(num) + "%";
    }

    @RequestMapping("attributes")
    public String repurchaseAttributes(Model model, HttpServletRequest request) {

	    String chooseTime = request.getParameter("chooseTime");
         
        // 初始化列表
        List<RepurchaseRateVO> repurchaseRateList = new ArrayList<>();
        for (NewCategoryEnum en : NewCategoryEnum.values()) {
            if (StringUtils.isNotEmpty(en.getShowName())) {
                RepurchaseRateVO vo = new RepurchaseRateVO();
                vo.setCategoryName(en.getValue());
                vo.setCateforyShowName(en.getShowName());
                repurchaseRateList.add(vo);
            }
        }

        RepruchaseAnalysisQuery query = new RepruchaseAnalysisQuery();
        
        if (!StringUtils.isEmpty(chooseTime)){
        	try {
        		Map<String, Date> map = DateUtil.getSelectDate(chooseTime);
				if(map != null && !map.isEmpty() && map.containsKey("beginDate") && map.containsKey("endDate")){
	         		query.setStartTime(map.get("beginDate"));
	         		query.setEndTime(map.get("endDate"));
	 	         }
        	} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
         	
        }else {
        	// 查询最近记录
        	RepruchaseAnalysis repruchaseAnalysis = repurchaseService.selectLatestRecord();
            query.setCreateTime(repruchaseAnalysis.getCreateTime());
        }
        // 上游复购率
        query.setBusinessType(NewCategoryEnum.UP_REPURCHASE_RATE.getCode());
        List<RepruchaseAnalysis> upRepurchaseRateList = repurchaseService.queryRepruchaseAnalysisList(query);
        for (RepruchaseAnalysis upRepurchaseRate : upRepurchaseRateList) {
            for (RepurchaseRateVO vo : repurchaseRateList) {
                if (vo.getCategoryName().equals(upRepurchaseRate.getCategory())) {
                    vo.setUpRepurchaseRate(new BigDecimal(upRepurchaseRate.getNum()).multiply(new BigDecimal("100")).toString());
                }
            }
        }

        // 下游复购率
        query.setBusinessType(NewCategoryEnum.DOWN_REPURCHASE_RATE.getCode());
        List<RepruchaseAnalysis> downRepurchaseRateList = repurchaseService.queryRepruchaseAnalysisList(query);
        for (RepruchaseAnalysis downRepurchaseRate : downRepurchaseRateList) {
            for (RepurchaseRateVO vo : repurchaseRateList) {
                if (vo.getCategoryName().equals(downRepurchaseRate.getCategory())) {
                    vo.setDownRepurchaseRate(new BigDecimal(downRepurchaseRate.getNum()).multiply(new BigDecimal("100")).toString());
                }
            }
        }

        // 自复购率
        query.setBusinessType(NewCategoryEnum.SELF_REPURCHASE_RATE.getCode());
        List<RepruchaseAnalysis> selfRepurchaseRateList = repurchaseService.queryRepruchaseAnalysisList(query);
        for (RepruchaseAnalysis selfRepurchaseRate : selfRepurchaseRateList) {
            for (RepurchaseRateVO vo : repurchaseRateList) {
                if (vo.getCategoryName().equals(selfRepurchaseRate.getCategory())) {
                    vo.setSelfRepurchaseRate(new BigDecimal(selfRepurchaseRate.getNum()).multiply(new BigDecimal("100")).toString());
                }
            }
        }

        // 交叉复购率
        query.setBusinessType(NewCategoryEnum.ACROSS_REPURCHASE_RATE.getCode());
        List<RepruchaseAnalysis> acrossRepurchaseRateList = repurchaseService.queryRepruchaseAnalysisList(query);
        for (RepruchaseAnalysis acrossRepurchaseRate : acrossRepurchaseRateList) {
            for (RepurchaseRateVO vo : repurchaseRateList) {
                if (vo.getCategoryName().equals(acrossRepurchaseRate.getCategory())) {
                    vo.setAcrossRepurchaseRate(new BigDecimal(acrossRepurchaseRate.getNum()).multiply(new BigDecimal("100")).toString());
                }
            }
        }

        List<String> chart1List = new ArrayList<>();
        List<String> chart2List = new ArrayList<>();

        for (RepurchaseRateVO vo : repurchaseRateList) {
            String chart1 = "[" + vo.getUpRepurchaseRate() + "," + vo.getDownRepurchaseRate() + ", 30 ,\'" + vo.getCateforyShowName() + "\',001]";
            chart1List.add(chart1);
            String chart2 = "[" + vo.getSelfRepurchaseRate() + "," + vo.getAcrossRepurchaseRate() + ", 30 ,\'" + vo.getCateforyShowName() + "\',002]";
            chart2List.add(chart2);
        }
        if (!StringUtils.isEmpty(chooseTime)){
        	model.addAttribute("chooseTime", chooseTime);
        }
        model.addAttribute("repurchaseChart1", Arrays.deepToString(chart1List.toArray()));
        model.addAttribute("repurchaseChart2", Arrays.deepToString(chart2List.toArray()));
        return "/application/repurchase/repurchaseAttributes";
    }

}
